const models = require('../db/mysqldb/index')
const sequelize = require('sequelize/index')
const Op = sequelize.Op
const {
  ErrorModel,
  SuccessModel,
  queryFilter
} = require('../utils/index')
const logger = require('../utils/logger')
const _ = require('lodash')
class SysRoleController {
  /**
   * @description 获取角色列表
   * @param {*} page 
   * @param {*} limit 
   */
  static async roleList (req, res, next) {
    let { page, limit } = req.query
    logger.info(`SysRoleController`, `roleList`, `req.query`, req.query)
    page = _.toNumber(page)
    limit = _.toNumber(limit)
    const filter = queryFilter(req.query)
    if (page <= 0) {
      page = 1
    }
    if (limit <= 0) {
      limit = 20
    }
    const offset = (page - 1) * limit
    logger.info(`SysRoleController`, `roleList`, `offset`, offset)
    try {
      // 模糊查询
      const resInfo = await models.sys_role.findAndCountAll({
        where: filter,
        limit,
        offset
      })
      logger.info(`SysRoleController`, `roleList`, `res`, resInfo)
      Object.assign(resInfo)
      res.json(new SuccessModel(resInfo, `查询成功`))
    } catch (error) {
      logger.error(`SysRoleController`, `roleList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 新增角色
   * @param {*} role_name 
   * @param {*} role_code 
   * @param {*} role_desc 
   */
  static async roleAdd (req, res, next) {
    const {
      role_name,
      role_code,
      role_desc
    } = req.body
    logger.info(`SysRoleController`, `roleAdd`, `req.body`, req.body)
    if (!role_name || !role_code) {
      res.json(new ErrorModel([], `缺少必填项`))
      return
    }
    try {
      const userFind = await models.sys_role.findOne({
        where: {
          [Op.or]: [
            {
              role_name: {
                [Op.eq]: role_name
              }
            },
            {
              role_code: {
                [Op.eq]: role_code
              }
            }
          ]
        }
      })
      logger.info(`SysRoleController`, `roleAdd`, `userFind`, userFind)
      if (userFind) {
        res.json(new ErrorModel([], `角色名称或角色码已存在`))
        return
      }
      const result = await models.sys_role.create({
        role_name,
        role_code,
        role_desc
      })
      logger.info(`SysRoleController`, `roleAdd`, `result`, result)
      res.json(new SuccessModel([], `新增角色成功`))
    } catch (error) {
      logger.error(`SysRoleController`, `roleAdd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 更新角色
   * @param {*} role_id 
   * @param {*} role_name 
   * @param {*} role_code 
   * @param {*} role_desc 
   */
  static async roleUpd (req, res, next) {
    const {
      role_id,
      role_name,
      role_code,
      role_desc
    } = req.body
    logger.info(`SysRoleController`, `roleUpd`, `req.body`, req.body)
    if (!role_id || !role_name || !role_code) {
      res.json(new ErrorModel([], `请输入必填项`))
      return
    }
    try {
      const userFind = await models.sys_role.findOne({
        where: {
          [Op.and]: [
            {
              role_id: {
                [Op.ne]: role_id,
              }
            },
            {
              [Op.or]: [
                {
                  role_name: {
                    [Op.eq]: role_name
                  }
                },
                {
                  role_code: {
                    [Op.eq]: role_code
                  }
                }
              ]
            }
          ]
        }
      })
      logger.info(`SysRoleController`, `roleAdd`, `userFind`, userFind)
      if (userFind) {
        res.json(new ErrorModel([], `已存在相同的角色名称或角色`))
        return
      }
      const result = await models.sys_role.update({
        role_name,
        role_code,
        role_desc,
        update_date_timestamp: Date.now()
      }, {
        where: { role_id }
      })
      logger.info(`SysRoleController`, `roleUpd`, `result`, result)
      res.json(new SuccessModel([], `角色更新成功`))
    } catch (error) {
      logger.error(`SysRoleController`, `roleUpd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除角色
   * @param {*} role_id 
   */
  static async roleDel (req, res, next) {
    const {
      role_id,
    } = req.body
    logger.info(`SysRoleController`, `roleDel`, `req.body`, req.body)
    if (!role_id) {
      res.json(new ErrorModel([], `role_id 获取失败`))
      return
    }
    try {
      const roleMenuDelInfo = await models.sys_role_menu.destroy({
        where: { role_id }
      })
      logger.info(`SysRoleController`, `roleDel`, `roleMenuDelInfo`, roleMenuDelInfo)
      const roleUserDelInfo = await models.sys_role_user.destroy({
        where: { role_id }
      })
      logger.info(`SysRoleController`, `roleDel`, `roleUserDelInfo`, roleUserDelInfo)
      const roleDelInfo = await models.sys_role.update({ del_flag: '1' }, {
        where: { role_id }
      })
      logger.info(`SysRoleController`, `roleDel`, `roleDelInfo`, roleDelInfo)
      res.json(new SuccessModel([], `删除角色成功`))
    } catch (error) {
      logger.error(`SysRoleController`, `roleDel`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 菜单权限配置
   * @param {*} role_id 
   * @param {*} menuIds 
   */
  static async roleMenu(req,res,next){
    const {menuIds,role_id} = req.body
    logger.info(`SysRoleController`, `roleDel`, `req.body`, req.body)
    try {
      if (!role_id) {
        res.json(new ErrorModel([], `role_id 获取失败`))
        return
      }
      // 根据role_id删除已有的绑定项
      const remove_role_menu_info = await models.sys_role_menu.destroy({
        where:{
          role_id
        }
      })
      logger.info(`SysRoleController`, `roleMenu`, `remove_role_menu_info`, remove_role_menu_info)
      const role_menu_list = menuIds.map(item=>{
        return {
          role_id,
          menu_id:item
        }
      })
      const add_role_menu_info = await models.sys_role_menu.bulkCreate(role_menu_list)
      logger.info(`SysRoleController`, `roleMenu`, `add_role_menu_info`, add_role_menu_info)
      res.json(new SuccessModel([], `更新成功`))
    } catch (error) {
      logger.error(`SysRoleController`, `roleMenu`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }    
  }
}

module.exports = {
  SysRoleController
}
